"use strict";
const EventEmitter = require('events').EventEmitter;

module.exports = function(timeout) {
    let self = this;
    let event = new EventEmitter();
    let waiters = [];
    let id = 0;
    timeout = timeout || 5000;
    this.acquire = function() {
        return new Promise((resolve, reject) => {
            id++;
            if (waiters.length == 0) {
                waiters.push(id);
                resolve();
            } else {
                waiters.push(id);
                event.once(id, function() {
                    resolve();
                });
            }
            ((id) => {
                setTimeout(() => {
                    if (waiters[0] == id) {
                        self.release();
                    }
                }, timeout);
            })(id);

        });

    };
    this.release = function() {
        waiters.shift();
        if (waiters.length) {
            event.emit(waiters[0]);
        }
    };
};
